//
//  LoginViewCtrl.m
//  DogeLegs
//
//  Created by 宋华 on 2017/8/16.
//  Copyright © 2017年 宋华. All rights reserved.
//

#import "LoginViewCtrl.h"
#import "RegistViewCtrlOne.h"
#import "BaseNavCtrl.h"
#import "NetRequest+user.h"
#import "BotLineTextField.h"

@interface LoginViewCtrl ()


@property (weak, nonatomic) IBOutlet BotLineTextField *emailTextField;

@property (weak, nonatomic) IBOutlet BotLineTextField *passwordTextFiled;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConstraint;

@property (weak, nonatomic) IBOutlet UIButton *signInBtn;
@property (weak, nonatomic) IBOutlet UIImageView *logoImageview;

- (IBAction)login:(id)sender;

- (IBAction)forgetPassword:(id)sender;

- (IBAction)signUp:(id)sender;

@property (nonatomic,strong)NSString *emailAddress;

@property (nonatomic,strong)NSString *password;



@end

@implementation LoginViewCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addNotifications];
    [self layoutsubViews];
   
    [self fillEmailFromCache];
    //测试代码
    [self.emailTextField setText:@"877340657@qq.com"];
    [self.passwordTextFiled setText:@"sdsdsds"];
    [self login:nil];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 通知
- (void)addNotifications {
    [NSNotificationCenter addCreatePwNF:self action:@selector(createPwDone:)];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardDidChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
}

#pragma mark  - 界面
- (void)layoutsubViews {
    setCornerRadius(self.signInBtn, 20.0f);
    self.emailTextField.botColor = [UIColor orangeColor];
 
}

- (void)fillEmailFromCache {
    bool is_login=[kUserDefaults boolForKey:IS_LOGIN];
    if (is_login) {
        NSString *email = [kUserDefaults objectForKey:LOGIN_EmailAddress];
        [self.emailTextField setText:email];
    }
}

#pragma mark - action事件

- (IBAction)login:(id)sender {
    [self requestlogin:NO];
}

- (IBAction)forgetPassword:(id)sender {

}

- (IBAction)signUp:(id)sender {
    RegistViewCtrlOne *registCtrl = [[RegistViewCtrlOne alloc] initWithNibName:@"RegistViewCtrlOne" bundle:nil];
    BaseNavCtrl *rNav = [[BaseNavCtrl alloc] initWithRootViewController:registCtrl];
    [self presentViewController:rNav animated:YES completion:nil];
}

#pragma mark -通知事件
- (void)createPwDone:(NSNotification *)not {
    NSString *emailAddress = [kUserDefaults objectForKey:LOGIN_EmailAddress];
    NSString *passWord = [kUserDefaults objectForKey:LOGIN_PASSWord];
    //自动登录 auto login
    self.emailTextField.text = emailAddress;
    self.passwordTextFiled.text = passWord;
    [self requestlogin:YES];
}

-(void)keyboardWillChangeFrame:(NSNotification *)notification{
    
    NSDictionary *userInfo = notification.userInfo;
    // 动画的持续时间
    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 键盘的frame
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSLog(@"%@",NSStringFromCGRect(keyboardF));
    
    CGFloat keheight = keyboardF.size.height;
    CGFloat keyY = keyboardF.origin.y;
    
    if (self.signInBtn.bottom > keyY) {
        [UIView animateWithDuration:duration animations:^{
            self.topConstraint.constant = keyY - self.logoTopToSignBtnBot;
            [self.view layoutIfNeeded];
        }];
    }
    if (keyY >= kScreenHeight && self.topConstraint.constant != 100) {
        [UIView animateWithDuration:duration animations:^{
            self.topConstraint.constant = 100;
            [self.view layoutIfNeeded];
        }];
    }

}

-(void)keyboardDidChangeFrame:(NSNotification *)notification{
    
    NSDictionary *userInfo = notification.userInfo;
    // 动画的持续时间
    //    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 键盘的frame
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        NSLog(@"%@",NSStringFromCGRect(keyboardF));
    
 
}


#pragma mark - 网络请求
- (void)requestlogin:(BOOL)autoLogin {
    if (![self isAllParamsVaild]) {
        return;
    }
    WeakSelf(ws);
    NSString *loginDesc = autoLogin ? @"autoLoging...":@"loging...";
    [SVProgressHUD showWithStatus:loginDesc];
    NSURLSessionDataTask *dataTask =
    [[LoginManager sharedInstance] loginDictorany:@{LOGIN_EmailAddress:self.emailAddress,LOGIN_PASSWord:self.password} success:^(UserMode *user) {
        [SVProgressHUD dismiss];
        [ws loginSuccess];
    } failed:^(RequestError *error) {
        [SVProgressHUD showErrorWithStatus:error.errorMsg];
        //暂时这么写
        [ws loginSuccess];
    }];
    [self addSessionDataTask:dataTask];
}

- (void)loginSuccess {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark -判断参数是否合法
- (BOOL)isAllParamsVaild {
    if (!isVailedEmail(self.emailAddress)) {
        [SVProgressHUD showErrorWithStatus:@"EmailAddress is invaild"];
        return NO;
    }
    if (self.password.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"Input your password"];
        return NO;
    }
    return YES;
}

#pragma mark - inherit
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];

}
#pragma mark - getter
- (NSString *)emailAddress {
    NSString *email =  [_emailTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return email;
}
- (NSString *)password {
    NSString *password =  [_passwordTextFiled.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return password;
}

- (CGFloat)logoTopToSignBtnBot {
    return self.signInBtn.bottom - self.logoImageview.top;
}

@end
